import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/*Server object that creates finger table used for node forwarding and creates receiver
thread that processes requests*/

public class Server {

	public ArrayList<MachineData> machines;
	
	public int N; //number of nodes
	public int index;
	public FingerTable table; //table used to determine where to forward
	
	public Receiver r;
	public ConcurrentHashMap<Integer,String> keys; //stores key value pairs
	
	public Server(int index, ArrayList<MachineData> machines) {
		
		this.N = machines.size();
		this.index = index;
		
		//create finger table
		this.table = new FingerTable(machines, index);
		//System.out.println("Server: " + index + " table size: " + table.table.size() + " entry 1: " + table.tableList.get(0) + " entry 2: " + table.tableList.get(1));
		//System.out.println(" entry 3: " + table.tableList.get(2));
		
		//initialize keys
		keys = new ConcurrentHashMap<Integer,String>();
		
		if(Global.readin) {
			ArrayList<String> lines = (new FileRead("keys.txt")).getLines();
			initKeys(lines);
		}
		
		//make receiver
		r = new Receiver(machines.get(index), table, keys);
		r.start();
		
	}
	
	//used to load in keys
	public void initKeys(ArrayList<String> lines) {
		
		for(String s: lines) {
			String[] arr = s.split("\\s");
			int k = Integer.parseInt(arr[0]);
			if(k % N == this.index) {
				keys.put(new Integer(k), arr[1]);
			}
		}
	}
}
